package com.sendinfo;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {

	@Value("${file.rootPath:./UploadFiles}")
	private String rootPath;

	private static final Logger logger = LoggerFactory.getLogger(FileController.class);

	/**
	 * 
	 * @param request
	 * @param file
	 * @return
	 */
	@RequestMapping(value = "/upload/{projectName}", method = RequestMethod.POST)
	public FileRes upload(HttpServletRequest request, @PathVariable("projectName") String projectName,
			@RequestParam("file") MultipartFile file, HttpServletResponse response) {

		FileRes res = FileRes.getErrorRes("1", "文件为空!");
		if (!file.isEmpty()) {
			try {
				String toDay = new SimpleDateFormat("yyyyMMdd").format(new Date());
				String relativePath = "/" + projectName + "/" + toDay.substring(0, 4) + "/" + toDay.substring(4, 6)
						+ "/" + toDay.substring(6, 8) + "/";
				String fileName = file.getOriginalFilename();
				fileName = toDay + "_" + fileName;
				// 图片所在路径
				String savePath = rootPath + relativePath + fileName;
				logger.info("上传文件到：" + savePath);
				File dest = new File(savePath);
				// 检测是否存在目录
				if (!dest.getParentFile().exists()) {
					dest.getParentFile().mkdirs();
				}
				// 输出文件到服务器本地
				BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
				out.write(file.getBytes());
				out.flush();
				out.close();
				res.toSuccessRes(fileName);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				logger.error(e.getMessage());
				res.toErrorRes("1", "上传失败," + e.getMessage());
			} catch (IOException e) {
				e.printStackTrace();
				logger.error(e.getMessage());
				res.toErrorRes("1", "上传失败," + e.getMessage());
			}
		} else {
			res.toErrorRes("1", "上传失败，因为文件是空的.");
		}
		return res;
	}

	// 文件下载相关代码
	@RequestMapping("/download/{projectName}/{fileName:.+}") /// {fileName:[a-zA-Z0-9\\.\\/]+}
	@ResponseBody
	public FileRes downloadFile(HttpServletRequest request, @PathVariable("projectName") String projectName,
			@PathVariable("fileName") String fileName, HttpServletResponse response) {

		FileRes res = FileRes.getErrorRes("1", "该文件不存在");
		// response.setContentType("application/json;charset=UTF-8");
		if (fileName != null) {
			logger.info("下载文件：" + fileName);
			String fileDay = fileName.substring(0, fileName.indexOf("_"));
			String relativePath = "/" + projectName + "/" + fileDay.substring(0, 4) + "/" + fileDay.substring(4, 6)
					+ "/" + fileDay.substring(6, 8) + "/";
			File file = new File(rootPath + relativePath, fileName);
			if (file.exists()) {
				response.setContentLengthLong(file.length()); // 设置下载文件大小
				// response.setContentType("application/force-download");//
				// 设置强制下载不打开
				// response.addHeader("Content-Disposition",
				// "attachment;fileName=" + fileName);// 设置文件名
				byte[] buffer = new byte[1024];
				FileInputStream fis = null;
				BufferedInputStream bis = null;
				OutputStream os = null;
				try {
					fis = new FileInputStream(file);
					bis = new BufferedInputStream(fis);
					os = response.getOutputStream();
					int i = bis.read(buffer);
					while (i != -1) {
						os.write(buffer, 0, i);
						os.flush();
						i = bis.read(buffer);
					}
					res.toSuccessRes("下载成功");
					return null;
				} catch (Exception e) {
					res.toErrorRes("2", "下载错误");
					// logger.error(e.getMessage());
					// e.printStackTrace();
				} finally {
					if (fis != null) {
						try {
							fis.close();
						} catch (IOException e) {
							e.printStackTrace();
							// logger.error(e.getMessage());
						}
					}
					if (bis != null) {
						try {
							bis.close();
						} catch (IOException e) {
							e.printStackTrace();
							// logger.error(e.getMessage());
						}
					}
				}
			} else {
				res.toErrorRes("1", "该文件不存在");
			}
		} else {
			res.toErrorRes("1", "请传入文件名称");
		}
		// 只有失败了才会返回res，json对象
		return res;
	}

	// 文件下载相关代码
	@RequestMapping("/delete/{projectName}/{fileName:.+}") /// {fileName:[a-zA-Z0-9\\.\\/]+}
	public FileRes deleteFile(HttpServletRequest request, @PathVariable("projectName") String projectName,
			@PathVariable("fileName") String fileName, HttpServletResponse response) {

		FileRes res = FileRes.getErrorRes("1", "该文件不存在");
		if (fileName != null) {
			logger.info("删除文件：" + fileName);
			String fileDay = fileName.substring(0, fileName.indexOf("_"));
			String relativePath = "/" + projectName + "/" + fileDay.substring(0, 4) + "/" + fileDay.substring(4, 6)
					+ "/" + fileDay.substring(6, 8) + "/";
			File file = new File(rootPath + relativePath, fileName);
			if (file.exists()) {
				if (file.delete()) {
					res.toSuccessRes("删除成功!");
				} else {
					res.toErrorRes("1", "删除失败!");
				}
			} else {
				res.toErrorRes("1", "该文件不存在");
			}
		} else {
			res.toErrorRes("1", "请传入文件名称");
		}
		return res;
	}

}
